package com.app.diary.ui;

import android.os.AsyncTask;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.app.diary.ApiClient;
import com.app.diary.data.impl.WeatherApiService;
import com.app.diary.data.model.WeatherResponse;

import retrofit2.Call;
import retrofit2.Response;

public class FetchWeatherTask extends AsyncTask<Void, Void, WeatherResponse> {

    private static final String TAG = "FetchWeatherTask";
    private final WeatherCallback callback;
    private final String location;
    private final String apiKey;

    public interface WeatherCallback {
        void onWeatherFetched(@Nullable String weatherInfo);
        void onErrorOccurred(String errorMessage);
        void onCancelled();
    }

    public FetchWeatherTask(WeatherCallback callback, String location, String apiKey) {
        this.callback = callback;
        this.location = location;
        this.apiKey = apiKey;
    }

    @Override
    protected WeatherResponse doInBackground(Void... voids) {
        if (isCancelled()) return null;

        try {
            WeatherApiService service = ApiClient.getClient().create(WeatherApiService.class);
            Call<WeatherResponse> call = service.getWeather(location, apiKey);
            Response<WeatherResponse> response = call.execute();

            if (response.isSuccessful() && response.body() != null) {
                return response.body();
            } else {
                Log.e(TAG, "Failed to fetch weather data: " + response.errorBody());
                return null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error fetching weather data", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(@Nullable WeatherResponse weatherResponse) {
        super.onPostExecute(weatherResponse);

        if (weatherResponse != null && weatherResponse.getNow() != null) {
            String weatherInfo = weatherResponse.getNow().getText() + ", " + weatherResponse.getNow().getTemp() + "°C";
            callback.onWeatherFetched(weatherInfo);
        } else {
            callback.onErrorOccurred("无法获取天气信息");
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        callback.onCancelled();
    }
}